package data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.rentapark.app.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;



//this class is an adapter implemented to handle requests list (seen by users that have requested parking spots)

public class OwnerListAdapter extends BaseAdapter implements OnClickListener{
	private Context context;
	private List<Request> RequestList;
	ProgressDialog progressDialog;
	DB parking_db;
	Request confirmed;

	//handles server's responses
	private final Handler handler = new Handler() {  

		public void handleMessage(Message msg) {
			String result = msg.getData().getString("RESPONSE"); 
			progressDialog.dismiss();
			Toast.makeText( context,result,Toast.LENGTH_LONG).show();

		} 
	};
//constructor
	public OwnerListAdapter(Context context, List<Request> RequestList) {
        this.context = context;
        this.RequestList = RequestList;
    }

	@Override
	public int getCount() {
		return RequestList.size();

	}

	@Override
	public Object getItem(int position) {
		return RequestList.get(position);

	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup viewGroup) {
		Request entry = RequestList.get(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.owner_list_row, null);
        }
        //setting all list's parameters
        TextView address = (TextView) convertView.findViewById(R.id.address);
        address.setText(entry.address);
       
        TextView name = (TextView) convertView.findViewById(R.id.BuyingName);
        name.setText(entry.candidateName);
        
        TextView grade = (TextView) convertView.findViewById(R.id.BuyingGrade);
        grade.setText(Integer.toString(entry.candidateGrade));
        Log.d("address is: ",entry.address);
        


       // Set the onClick Listener on this button
        //this button is used when the spot's owner wants to accept some request
        Button btnConfirm = (Button) convertView.findViewById(R.id.AcceptBtm);
        btnConfirm.setFocusableInTouchMode(false);
        btnConfirm.setFocusable(false);
        btnConfirm.setOnClickListener((android.view.View.OnClickListener) this);
        // Set the entry, so that you can capture which item was clicked 
        btnConfirm.setTag(entry);
  

        return convertView;
    }

	@Override
	public void onClick(View v) {
		confirmed=(Request)v.getTag();//get clicked entry
		parking_db=DB.getInstance();
		//saving information about the buyer candidate
		parking_db.userDealId=confirmed.candidateId;
		parking_db.userDealPhone=confirmed.candidatePhone;
		parking_db.spotRentId=confirmed.spotId;
		//send confirm msg to server: spot's owner accepts request
		performConfirm("http://"+parking_db.instanceDNS+":8080/ParkAndLetPark/OwnersConfirm");
		
	}
	private void performConfirm(final String uri) { 
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {    
				//StatusLine status = response.getStatusLine();        
				HttpEntity entity = response.getEntity();          
				String result = null; 
				try { 
					result = data.CommonUtilities.inputStreamToString(entity.getContent());   
					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);         
				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 


		this.progressDialog = ProgressDialog.show(context, "Executing", "confirmation");
		// create and run the thread that perform the request and handle the response
		new Thread() {                          
			@Override 
			public void run() { 
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(uri);
				try {
					try{
						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();

						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Request = doc.createElement("MSG_TYPE");
						Request.appendChild(doc.createTextNode("OWNER_CONFIRM"));
						doc.appendChild(Request);

						Element Userid=doc.createElement("USER_ID");
						Userid.appendChild(doc.createTextNode(Double.toString(parking_db.userID)));//can be 0 on newUser!!
						Request.appendChild(Userid);
						
						Element spotId=doc.createElement("SPOT_ID");
						spotId.appendChild(doc.createTextNode(Integer.toString(confirmed.spotId)));//can be 0 on newUser!!
						Userid.appendChild(spotId);
						
						Element otherId=doc.createElement("CAND_ID");
						otherId.appendChild(doc.createTextNode(Double.toString(confirmed.candidateId)));//can be 0 on newUser!!
						spotId.appendChild(otherId);


						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString",xmlString);


						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);

						String response = httpclient.execute(httppost,responseHandler);
						Log.d("","*server response* "+response);
					}
					catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					}

				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}
			}

		}.start(); 
	}

}
